const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatDate = (startTime)=>{
  //当前时间与2017-04-04的时间差
  // let startTime = "20171225093900";
  let formatDateStr = startTime.substring(0, 4) + "/" + startTime.substring(4, 6) + "/" + startTime.substring(6, 8) + " " + startTime.substring(8, 10) + ":" + startTime.substring(10, 12) + ":" + startTime.substring(12, 14);
  let startDate = new Date(formatDateStr);
  let endDate = new Date();
  let diff = endDate.getTime() - startDate.getTime();//时间差的毫秒数  

  //计算出相差天数  
  let days = Math.floor(diff / (24 * 3600 * 1000));

  //计算出小时数  
  let leave1 = diff % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数  
  let hours = Math.floor(leave1 / (3600 * 1000));
  //计算相差分钟数  
  let leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数  
  let minutes = Math.floor(leave2 / (60 * 1000));

  //计算相差秒数  
  let leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数  
  let seconds = Math.round(leave3 / 1000);
  let returnStr = "刚刚";
  if (minutes > 0) {
    returnStr = minutes + "分钟前";
  }
  if (hours > 0) {
    returnStr = hours + "小时前";
  }
  if (days > 0) {
    if (days == 1) {
      returnStr = "昨天";
    } else if (days == 2) {
      returnStr = "前天";
    } else {
      returnStr = startTime.substring(0, 4) + "-" + startTime.substring(4, 6) + "-" + startTime.substring(6, 8);
    }
  }
  return returnStr;
}

const sortByTime = (tempList)=> {
  var map = {},dest = [];
  for (var i = 0; i < tempList.length; i++) {
    var ai = tempList[i];
    if (!map[ai.time.substring(0, 8)]) {
      dest.push({
        initial: ai.time,
        busInfoList: [ai]
      });
      map[ai.time.substring(0, 8)] = ai;
    } else {
      for (var j = 0; j < dest.length; j++) {
        var dj = dest[j];
        if (dj.initial.substring(0, 8) == ai.time.substring(0, 8)) {
          dj.busInfoList.push(ai);
          break;
        }
      }
    }
  }
  return dest;
}
// 邮箱验证
const fChkMail = (mail) => {
  var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  return reg.test(mail);
}

// 手机号验证
const isValidNo = (mobileNo) => {
  var v = false;
  if (mobileNo == null || mobileNo == "" || mobileNo.length != 11) {
    return false;
  }
  var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(14[0-9]{1}))+\d{8})$/;
  if (myreg.test(mobileNo)) {
    v = true;
  }
  return v;
}
module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  sortByTime: sortByTime,
  fChkMail: fChkMail,
  isValidNo: isValidNo
}
